# -*- coding: utf-8 -*-
"""
Created on Fri Feb  1 22:08:28 2019
python3.6.3
Anaconda->spyder
opencv3.4.5
代码参考《OpenCV3计算机视觉 Python语言实现》（第二版）
@author: Administrator
"""


import cv2
import numpy as np

img = cv2.pyrDown(cv2.imread('pycv.png',cv2.IMREAD_UNCHANGED))
img2 = img.copy()

ret,thresh = cv2.threshold(cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY),127,255,cv2.THRESH_BINARY)
image,contours,hier = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

"""
三种写法
"""
'''方法一'''
for c in contours:
    #拟合误差值，越小轮廓画的越好
    epsilion = 0.001 * cv2.arcLength(c,True)
#    print(epsilion)
#    计算多边形边框
    approx = cv2.approxPolyDP(c,epsilion,True) 
    approx_np = np.array(approx)
#    print('approx.shape: ', approx_np.shape)
    #print('approx[0]: ', approx_np[0])
    #另一种计算轮廓方式
    hull = cv2.convexHull(c)
    hull_np = np.array(hull)
#    print('hull_np.shape: ', hull_np.shape)

cv2.drawContours(img2,[hull],-1,(255,0,0),2) # 任取一个cv2.drawContours(img2,[approx],-1,(255,0,0),2)
cv2.imshow('contours',img2)
cv2.waitKey()
cv2.destroyAllWindows()

"""
'''方法二'''
for c in contours:
    epsilion = 0.01 * cv2.arcLength(c,True)
    approx = cv2.approxPolyDP(c,epsilion,True) 
    hull = cv2.convexHull(c)
    cv2.polylines(img2, [hull], True, (0, 0, 255), 2)

cv2.imshow('contours',img2)
cv2.waitKey()
cv2.destroyAllWindows()


'''方法三'''
for c in contours:
    epsilion = 0.01 * cv2.arcLength(c,True)
    approx = cv2.approxPolyDP(c,epsilion,True) 
    hull = cv2.convexHull(c)
    cv2.drawContours(img2,[hull],-1,(255,0,0),2)

cv2.imshow('contours',img2)
cv2.waitKey()
cv2.destroyAllWindows()
"""


